package com.yaxin.outsourcing.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.util.Matrix;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 单张临时工作证生成工具（返回 PDDocument）
 */
public class CardPrinterUtil {

    // 名片尺寸（9cm × 5.5cm 转换为点，1cm = 28.35pt）
    public static final float CARD_WIDTH = 9.0f * 28.35f;   // ≈ 255 pt
    public static final float CARD_HEIGHT = 5.5f * 28.35f; // ≈ 156 pt

    /**
     * 生成单张名片 PDF（返回 PDDocument，不保存到文件）
     */
    public static PDDocument generateCard(String name,
                                          String dept,
                                          String id,
                                          String logoPath,
                                          String photoPath,
                                          BufferedImage qrImage) {
        try {
            PDDocument document = new PDDocument();
            PDPage page = new PDPage(new PDRectangle(CARD_WIDTH, CARD_HEIGHT));
            document.addPage(page);

            PDPageContentStream content = new PDPageContentStream(document, page);

            // 背景色
            content.setNonStrokingColor(255, 255, 255); // 粉色
            content.addRect(0, 0, CARD_WIDTH, CARD_HEIGHT);
            content.fill();


// 保存当前图形状态
            content.saveGraphicsState();

// 设置水印字体和颜色
            PDFont liShuFont = getLiShuFont(document);
            content.setFont(liShuFont, 10);
            content.setNonStrokingColor(200, 200, 200);

// 定义多个水印位置
            float[][] positions = {
                {CARD_WIDTH/3 - 10, CARD_HEIGHT/3 - 10},
                {CARD_WIDTH/3 - 10, 2 * CARD_HEIGHT/3 - 10},
                {CARD_WIDTH/3 - 10, CARD_HEIGHT - 10},
                {2*CARD_WIDTH/3 - 10, CARD_HEIGHT/3 - 10},
                {2*CARD_WIDTH/3 - 10, 2 * CARD_HEIGHT/3 - 10},
                {2*CARD_WIDTH/3 - 10, CARD_HEIGHT - 10},
                {CARD_WIDTH - 10, CARD_HEIGHT/3 - 10},
                {CARD_WIDTH - 10, 2 * CARD_HEIGHT/3 - 10},
                {CARD_WIDTH - 10, CARD_HEIGHT - 10}
                /* ---- */

            };

// 绘制多条45度倾斜水印
            for (float[] pos : positions) {
                float centerX = pos[0];
                float centerY = pos[1];

                // 保存当前状态
                content.saveGraphicsState();

                // 移动到中心点，旋转45度，再移动回原位置
                content.transform(Matrix.getTranslateInstance(centerX, centerY));
                content.transform(Matrix.getRotateInstance(Math.toRadians(45), 0, 0));
                content.transform(Matrix.getTranslateInstance(-centerX, -centerY));

                // 绘制水印文本
                content.beginText();
                content.newLineAtOffset(centerX - 30, centerY - 5);
                content.showText("连云港亚新");
                content.endText();

                // 恢复状态
                content.restoreGraphicsState();
            }

// 恢复图形状态
            content.restoreGraphicsState();

            // Logo
            if (logoPath != null && new File(logoPath).exists()) {
                PDImageXObject logo = PDImageXObject.createFromFile(logoPath, document);

                // 获取图片原始尺寸
                float originalWidth = logo.getWidth();
                float originalHeight = logo.getHeight();

                // 定义目标高度
                float targetHeight = 30;

                // 根据原始宽高比计算宽度
                float targetWidth = (originalWidth * targetHeight) / originalHeight;

                // 放置在左上角: 距离左边和顶部各10个点
                float logoX = 10;  // 距离左边10个点
                float logoY = CARD_HEIGHT - targetHeight - 10;  // 距离顶部10个点

                content.drawImage(logo, logoX, logoY, targetWidth, targetHeight);
            }

            // 中文字体
            PDType0Font chineseFont = loadChineseFont(document);

            // 标题
            content.beginText();
            content.setNonStrokingColor(255, 0, 0); // 红色
            content.setFont(chineseFont, 15);
            float titleWidth = (float) (15 * 3.0);
            float titleX = (CARD_WIDTH - titleWidth) / 2;
            content.newLineAtOffset(titleX, CARD_HEIGHT - 65);
            content.showText("临时工作证");
            content.endText();

            // 照片
            if (photoPath != null && new File(photoPath).exists()) {
                PDImageXObject photo = PDImageXObject.createFromFile(photoPath, document);
                content.drawImage(photo, 10, CARD_HEIGHT - 135, 60, 72);
            }

            // 文字信息
            content.beginText();
            content.setNonStrokingColor(0, 0, 0);
            content.setFont(chineseFont, 10);
            content.newLineAtOffset(80, CARD_HEIGHT - 90);
            content.showText("姓名：" + name);
            content.endText();

            content.beginText();
            content.setFont(chineseFont, 10);
            content.newLineAtOffset(80, CARD_HEIGHT - 110);
            content.showText("编号：" + id);
            content.endText();

            // 部门信息（支持多行显示）
            content.beginText();
            content.setFont(chineseFont, 10);
            content.newLineAtOffset(80, CARD_HEIGHT - 130);

            String deptLabel = "单位：";
            int maxCharsPerLine = 11;
            String fullDeptText = deptLabel + dept;

// 按每行最多8个字符分割文本
            int startY = 120;
            int lineHeight = 15;
            int lineIndex = 0;

            for (int i = 0; i < fullDeptText.length(); i += maxCharsPerLine) {
                int endIndex = Math.min(i + maxCharsPerLine, fullDeptText.length());
                String line = fullDeptText.substring(i, endIndex);

                if (lineIndex > 0) {
                    content.endText();
                    content.beginText();
                    content.setFont(chineseFont, 10);
                    content.newLineAtOffset(110, CARD_HEIGHT - startY - (lineIndex * lineHeight) - 8);
//                    content.newLineAtOffset(80, startY - (lineIndex * lineHeight));
                }

                content.showText(line);
                lineIndex++;
            }

            content.endText();

            // 二维码（直接用 BufferedImage）
            if (qrImage != null) {
                PDImageXObject qrCode = PDImageXObject.createFromByteArray(
                    document,
                    bufferedImageToBytes(qrImage),
                    "qrcode"
                );
                content.drawImage(qrCode, CARD_WIDTH - 63, 19, 61, 61);
            }

            // 增加四角边框
            // 在绘制完其他内容后，添加四个角的红色边框
// 右上角边框
            content.setStrokingColor(255, 0, 0); // 红色
            content.setLineWidth(2);
            content.moveTo(CARD_WIDTH - 20, CARD_HEIGHT);
            content.lineTo(CARD_WIDTH, CARD_HEIGHT);
            content.lineTo(CARD_WIDTH, CARD_HEIGHT - 20);
            content.stroke();

// 左上角边框
            content.moveTo(0, CARD_HEIGHT);
            content.lineTo(0, CARD_HEIGHT - 20);
            content.moveTo(0, CARD_HEIGHT);
            content.lineTo(20, CARD_HEIGHT);
            content.stroke();

// 左下角边框
            content.moveTo(0, 0);
            content.lineTo(0, 20);
            content.moveTo(0, 0);
            content.lineTo(20, 0);
            content.stroke();

// 右下角边框
            content.moveTo(CARD_WIDTH, 0);
            content.lineTo(CARD_WIDTH - 20, 0);
            content.moveTo(CARD_WIDTH, 0);
            content.lineTo(CARD_WIDTH, 20);
            content.stroke();


            content.close();
            return document;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成单张名片 PDF（返回 PDDocument，不保存到文件）- 使用 BufferedImage 作为照片
     */
    public static PDDocument generateCard(String name,
                                          String dept,
                                          String id,
                                          String logoPath,
                                          BufferedImage portraitImage, // 改为 BufferedImage
                                          BufferedImage qrImage) {
        try {
            PDDocument document = new PDDocument();
            PDPage page = new PDPage(new PDRectangle(CARD_WIDTH, CARD_HEIGHT));
            document.addPage(page);

            PDPageContentStream content = new PDPageContentStream(document, page);

            // 背景色
            content.setNonStrokingColor(255, 255, 255); // 白色
            content.addRect(0, 0, CARD_WIDTH, CARD_HEIGHT);
            content.fill();

            // 保存当前图形状态
            content.saveGraphicsState();

            // 设置水印字体和颜色
            PDFont liShuFont = getLiShuFont(document);
            content.setFont(liShuFont, 10);
            content.setNonStrokingColor(200, 200, 200);

            // 定义多个水印位置
            float[][] positions = {
                {CARD_WIDTH/3 - 10, CARD_HEIGHT/3 - 10},
                {CARD_WIDTH/3 - 10, 2 * CARD_HEIGHT/3 - 10},
                {CARD_WIDTH/3 - 10, CARD_HEIGHT - 10},
                {2*CARD_WIDTH/3 - 10, CARD_HEIGHT/3 - 10},
                {2*CARD_WIDTH/3 - 10, 2 * CARD_HEIGHT/3 - 10},
                {2*CARD_WIDTH/3 - 10, CARD_HEIGHT - 10},
                {CARD_WIDTH - 10, CARD_HEIGHT/3 - 10},
                {CARD_WIDTH - 10, 2 * CARD_HEIGHT/3 - 10},
                {CARD_WIDTH - 10, CARD_HEIGHT - 10}
            };

            // 绘制多条45度倾斜水印
            for (float[] pos : positions) {
                float centerX = pos[0];
                float centerY = pos[1];

                // 保存当前状态
                content.saveGraphicsState();

                // 移动到中心点，旋转45度，再移动回原位置
                content.transform(Matrix.getTranslateInstance(centerX, centerY));
                content.transform(Matrix.getRotateInstance(Math.toRadians(45), 0, 0));
                content.transform(Matrix.getTranslateInstance(-centerX, -centerY));

                // 绘制水印文本
                content.beginText();
                content.newLineAtOffset(centerX - 30, centerY - 5);
                content.showText("连云港亚新");
                content.endText();

                // 恢复状态
                content.restoreGraphicsState();
            }

            // 恢复图形状态
            content.restoreGraphicsState();

            // Logo
            if (logoPath != null && new File(logoPath).exists()) {
                PDImageXObject logo = PDImageXObject.createFromFile(logoPath, document);

                // 获取图片原始尺寸
                float originalWidth = logo.getWidth();
                float originalHeight = logo.getHeight();

                // 定义目标高度
                float targetHeight = 30;

                // 根据原始宽高比计算宽度
                float targetWidth = (originalWidth * targetHeight) / originalHeight;

                // 放置在左上角: 距离左边和顶部各10个点
                float logoX = 10;  // 距离左边10个点
                float logoY = CARD_HEIGHT - targetHeight - 10;  // 距离顶部10个点

                content.drawImage(logo, logoX, logoY, targetWidth, targetHeight);
            }

            // 中文字体
            PDType0Font chineseFont = loadChineseFont(document);

            // 标题
            content.beginText();
            content.setNonStrokingColor(255, 0, 0); // 红色
            content.setFont(chineseFont, 15);
            float titleWidth = (float) (15 * 3.0);
            float titleX = (CARD_WIDTH - titleWidth) / 2;
            content.newLineAtOffset(titleX, CARD_HEIGHT - 65);
            content.showText("临时工作证");
            content.endText();

            // 照片 - 主要修改部分
            if (portraitImage != null) {
                // 将 BufferedImage 转换为 PDImageXObject
                PDImageXObject photo = PDImageXObject.createFromByteArray(
                    document,
                    bufferedImageToBytes(portraitImage),
                    "portrait"
                );
                content.drawImage(photo, 10, CARD_HEIGHT - 135, 60, 72);
            }

            // 文字信息
            content.beginText();
            content.setNonStrokingColor(0, 0, 0);
            content.setFont(chineseFont, 10);
            content.newLineAtOffset(80, CARD_HEIGHT - 90);
            content.showText("姓名：" + name);
            content.endText();

            content.beginText();
            content.setFont(chineseFont, 10);
            content.newLineAtOffset(80, CARD_HEIGHT - 110);
            content.showText("编号：" + id);
            content.endText();

            // 部门信息（支持多行显示）
            content.beginText();
            content.setFont(chineseFont, 10);
            content.newLineAtOffset(80, CARD_HEIGHT - 130);

            String deptLabel = "单位：";
            int maxCharsPerLine = 11;
            String fullDeptText = deptLabel + dept;

            // 按每行最多8个字符分割文本
            int startY = 120;
            int lineHeight = 15;
            int lineIndex = 0;

            for (int i = 0; i < fullDeptText.length(); i += maxCharsPerLine) {
                int endIndex = Math.min(i + maxCharsPerLine, fullDeptText.length());
                String line = fullDeptText.substring(i, endIndex);

                if (lineIndex > 0) {
                    content.endText();
                    content.beginText();
                    content.setFont(chineseFont, 10);
                    content.newLineAtOffset(110, CARD_HEIGHT - startY - (lineIndex * lineHeight) - 8);
                }

                content.showText(line);
                lineIndex++;
            }

            content.endText();

            // 二维码（直接用 BufferedImage）
            if (qrImage != null) {
                PDImageXObject qrCode = PDImageXObject.createFromByteArray(
                    document,
                    bufferedImageToBytes(qrImage),
                    "qrcode"
                );
                content.drawImage(qrCode, CARD_WIDTH - 63, 19, 61, 61);
            }

            // 增加四角边框
            content.setStrokingColor(255, 0, 0); // 红色
            content.setLineWidth(2);

            // 右上角边框
            content.moveTo(CARD_WIDTH - 20, CARD_HEIGHT);
            content.lineTo(CARD_WIDTH, CARD_HEIGHT);
            content.lineTo(CARD_WIDTH, CARD_HEIGHT - 20);
            content.stroke();

            // 左上角边框
            content.moveTo(0, CARD_HEIGHT);
            content.lineTo(0, CARD_HEIGHT - 20);
            content.moveTo(0, CARD_HEIGHT);
            content.lineTo(20, CARD_HEIGHT);
            content.stroke();

            // 左下角边框
            content.moveTo(0, 0);
            content.lineTo(0, 20);
            content.moveTo(0, 0);
            content.lineTo(20, 0);
            content.stroke();

            // 右下角边框
            content.moveTo(CARD_WIDTH, 0);
            content.lineTo(CARD_WIDTH - 20, 0);
            content.moveTo(CARD_WIDTH, 0);
            content.lineTo(CARD_WIDTH, 20);
            content.stroke();

            content.close();
            return document;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * BufferedImage 转 byte[]
     */
    private static byte[] bufferedImageToBytes(BufferedImage image) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        return baos.toByteArray();
    }

    /**
     * 加载中文字体
     */
    private static PDType0Font loadChineseFont(PDDocument document) {
        List<String> fontPaths = new ArrayList<>();
        fontPaths.add("C:/Windows/Fonts/msyh.ttc");
        fontPaths.add("C:/Windows/Fonts/simsun.ttc");
        fontPaths.add("C:/Windows/Fonts/simhei.ttf");
        fontPaths.add("C:/Windows/Fonts/msyh.ttf");
        fontPaths.add("/usr/share/fonts/truetype/wqy/wqy-microhei.ttc");
        fontPaths.add("/System/Library/Fonts/PingFang.ttc");

        for (String path : fontPaths) {
            try {
                File fontFile = new File(path);
                if (fontFile.exists()) {
                    return PDType0Font.load(document, fontFile);
                }
            } catch (Exception ignored) {}
        }
        return null;
    }

    // 获取隶书字体的方法
    public static PDFont getLiShuFont(PDDocument document) {
        String os = System.getProperty("os.name").toLowerCase();

        if (os.contains("win")) {
            // Windows 系统隶书字体路径
            String[] liShuPaths = {
                "C:/Windows/Fonts/simli.ttf",      // 简体隶书
                "C:/Windows/Fonts/LiSu.ttf",       // 隶书
                "C:/Windows/Fonts/STLITI.ttf"      // 华文隶书
            };

            for (String path : liShuPaths) {
                try {
                    return PDType0Font.load(document, new File(path));
                } catch (IOException e) {
                    continue;
                }
            }
        } else if (os.contains("mac")) {
            // Mac 系统隶书字体路径
            String[] liShuPaths = {
                "/Library/Fonts/STLiti.ttf",       // 华文隶书
                "/System/Library/Fonts/STLiti.ttf"
            };

            for (String path : liShuPaths) {
                try {
                    return PDType0Font.load(document, new File(path));
                } catch (IOException e) {
                    continue;
                }
            }
        }

        // 如果找不到隶书字体，回退到其他书法字体
        return getCalligraphyFont(document);
    }

    // 获取其他书法字体作为备选
    public static PDFont getCalligraphyFont(PDDocument document) {
        String os = System.getProperty("os.name").toLowerCase();
        String[] fontPaths = {};

        if (os.contains("win")) {
            fontPaths = new String[]{
                "C:/Windows/Fonts/simkai.ttf",    // 楷体
                "C:/Windows/Fonts/simfang.ttf",   // 仿宋
                "C:/Windows/Fonts/simsun.ttc"     // 宋体
            };
        } else if (os.contains("mac")) {
            fontPaths = new String[]{
                "/Library/Fonts/STKaiti.ttf",     // 华文楷体
                "/System/Library/Fonts/PingFang.ttc"
            };
        }

        for (String path : fontPaths) {
            try {
                return PDType0Font.load(document, new File(path));
            } catch (IOException e) {
                continue;
            }
        }

        // 最终回退到默认字体
        return PDType1Font.HELVETICA;
    }
}
